package com.fesnakj.todos.jpa;

import javax.persistence.EntityManagerFactory;
import javax.persistence.Persistence;
import javax.servlet.ServletContextEvent;
import javax.servlet.ServletContextListener;

public class JPAContext implements ServletContextListener {

    private static EntityManagerFactory emf;

    public static EntityManagerFactory getEMF() {
        if (emf == null)
            createEntityManagerFactory();
        return emf;
    }

    public void contextInitialized(ServletContextEvent servletContextEvent) {
        createEntityManagerFactory();
    }

    public void contextDestroyed(ServletContextEvent servletContextEvent) {
        closeEntityManagerFactory();
    }

    // TODO add boolean return type which tells if entity created successfully
    public static void createEntityManagerFactory() {
        if (emf == null)
            emf = Persistence.createEntityManagerFactory("todos");
    }

    public static void closeEntityManagerFactory() {
        if (emf != null && emf.isOpen())
            emf.close();
    }
}
